<?php

namespace app\Http\Controllers\admins;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class Article extends Controller
{
    // 表单
    private function form($field = [])
    {
        $form = [
            ['label' => '标题', 'name' => 'title', 'verify' => 'required', 'class' => 'block', 'placeholder' => '请输入'],
            ['label' => '内容', 'name' => 'content', 'type' => 'editor', 'verify' => 'required', 'placeholder' => '请输入'],
            ['label' => '摘要', 'name' => 'excerpt', 'type' => 'textarea', 'rows' => 5],
            ['label' => '缩略图', 'name' => 'thumb', 'type' => 'upload'],
            ['label' => '分类', 'name' => 'cat_id', 'type' => 'select', 'value' => 0, 'verify' => 'required', 'options' => $this->cat_tree()],
            ['label' => '标签', 'name' => 'tags', 'desc' => '多个标签 , 分割'],
            ['label' => '别名', 'name' => 'slug'],
            ['label' => 'seo标题', 'name' => 'seo_title'],
            ['label' => 'seo描述', 'name' => 'seo_des', 'type' => 'textarea'],
            ['label' => '蜘蛛不索引', 'name' => 'robots', 'type' => 'switch'],
            ['label' => '状态', 'name' => 'status', 'type' => 'radio', 'value' => 0, 'options' => [0 => '启用', 1 => '禁用']],
        ];
        if ($field) {
            if (count($field) === count($field, 1)) {
                array_push($form, $field);
            } else {
                $form = array_merge($form, $field);
            }
        }
        return $form;
    }

    // 无限层级分类树
    private function cat_tree()
    {
        $db = DB::table('cat')
            ->orderBy('id', 'asc')
            ->orderBy('order', 'desc')
            ->get()
            ->all();
        $db = $this->trees($db);
        $db = array_reduce($db, function ($res, $next) {
            $res[$next->id] = $next->level ? str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;", $next->level) . "|— " . $next->name : $next->name;
            return $res;
        }, [0 => '&mdash; 顶级分类 &mdash;']);
        return $db;
    }

    public function index(Request $request)
    {
        if ($request->ajax()) {
            // $page = $request->page ?? 1;
            $limit = $request->limit ?? 10;
            $db = DB::table('article');
            // 搜索
            if (isset($request->search) && $request->search) {
                foreach ((array)$request->search as $k => $v) {
                    if ($v) $db = $db->where($k, 'like', "%{$v}%");
                }
            }
            $db = $db->where('is_del', 0)
                ->orderBy('id', 'desc');
            $data['count'] = $db->count();
            // 分页
            $db = $db->paginate($limit)->items();
            if ($data['count']) {
                $data['code'] = 0;
            } else {
                $data['code'] = 1;
                $data['msg'] = '暂无记录';
            }
            // 分类和标签
            $cats = DB::table('cat')->format('id');
            $tags = DB::table('tag')->format('id');
            // 格式化数据
            $data['data'] = array_map(function ($item) use ($cats, $tags) {
                $item->thumb = $item->thumb ? '<img src="' . $item->thumb . '" style="width:50px;height:30px;" />' : '';
                $item->excerpt = mb_strimwidth(strip_tags($item->excerpt), 0, 60, '...', 'utf-8');
                $item->cat_id = $item->cat_id && isset($cats[$item->cat_id]) ? $cats[$item->cat_id]->name : '';
                $item->tags = $item->tags ? implode(', ', array_reduce(array_map('trim', json_decode($item->tags)), function ($res, $next) use ($tags) {
                    $res[] = $tags[$next]->name;
                    return $res;
                }, [])) : '';
                $item->status = $item->status ? '禁用' : '启用';
                return $item;
            }, $db);
            return json_encode($data);
        }
        $form = [
            ['label' => '标题', 'name' => 'title', 'layui' => 'inline', 'placeholder' => '请输入'],
            ['label' => '摘要', 'name' => 'excerpt', 'layui' => 'inline', 'placeholder' => '请输入'],
            ['label' => '内容', 'name' => 'content', 'layui' => 'inline', 'placeholder' => '请输入'],
            ['type' => 'submit', 'filter' => 'search', 'layui' => 'inline', 'value' => '<i class="layui-icon layui-icon-search"></i>']
        ];
        $data['search'] = $this->build_form($form);
        $data['title'] = '文章列表';
        $data['prefix'] = '/admins/article';
        return view('/admins/article/index', $data);
    }

    public function add()
    {
        // 确保至少一个分类
        $data['title'] = '添加文章';
        $form = $this->form([
            ['type' => 'submit', 'value' => '保存'],
            ['type' => 'button', 'value' => '取消', 'filter' => 'cancel', 'btn' => 'primary']
        ]);
        $args = ['url' => '/admins/article/save', 'reload' => '/admins/article/index', 'upload' => '/admins/files/uploads'];
        $data['form'] = $this->build_form($form);
        $data['script'] = $this->build_script($form, $args);
        return view('/admins/article/add', $data);
    }

    public function save(Request $request)
    {
        $data = $this->check($this->form(), $request);
        if (!is_array($data)) return $data;
        $check = DB::table('article')->where('title', $data['title'])->first();
        if ($check) return $this->errMsg(1, '文章标题重复');
        if ($data['slug']) {
            $check = DB::table('article')->where('slug', $data['slug'])->first();
            if ($check) return $this->errMsg(1, '文章别名重复');
        }
        // 保存缩略图和内容中上传的附件
        if (preg_match_all('#["\'](/storage/.+?\.[^"\']*)["\']#i', str_replace('\\', '', json_encode($data)), $matches)) {
            foreach (array_unique($matches[1]) as $match) {
                DB::table('files')->where('path', $match)->update(['status' => 0]);
            }
        }
        // 保存标签
        $tags = [];
        if (isset($data['tags']) && $data['tags']) {
            foreach (array_map('trim', array_unique(explode(',', $data['tags']))) as $tag_name) {
                $tag = DB::table('tag')->where('name', $tag_name)->first();
                if ($tag) {
                    // 已有标签
                    $tags[] = $tag->id;
                } else {
                    // 新标签
                    $tags[] = DB::table('tag')->insertGetId(['name' => $tag_name]);
                }
            }
        }
        $data['tags'] = json_encode($tags);
        // 用户ID
        $user = Auth::user();
        $data['uid'] = $user->id;
        $res = DB::table('article')->insert($data);
        if (!$res) $this->errMsg(1, '保存失败');
        return $this->errMsg(0, '保存成功');
    }

    public function edit(Request $request)
    {
        $id = (int)$request->id;
        if (!$id) return $this->errMsg(1, '数据错误');
        $value = DB::table('article')->where('id', $id)->first();
        $tags = DB::table('tag')->format('id');
        $value->tags = isset($value->tags) && $value->tags ? implode(', ', array_reduce(array_map('trim', json_decode($value->tags)), function ($res, $next) use ($tags) {
            $res[] = $tags[$next]->name;
            return $res;
        }, [])) : '';
        $form = $this->form([
            ['name' => 'id', 'type' => 'hidden', 'value' => $id],
            ['type' => 'submit', 'value' => '保存'],
            ['type' => 'button', 'value' => '取消', 'filter' => 'cancel', 'btn' => 'primary']
        ]);
        $args = ['url' => '/admins/article/save_edit', 'reload' => '/admins/article/index', 'upload' => '/admins/files/uploads'];
        $data['title'] = '编辑文章';
        $data['form'] = $this->build_form($form, $value);
        $data['script'] = $this->build_script($form, $args);
        return view('/admins/article/edit', $data);
    }

    public function save_edit(Request $request)
    {
        $id = (int)$request->id;
        if (!$id) return $this->errMsg(1, '数据错误');
        $data = $this->check($this->form(), $request);
        if (!is_array($data)) return $data;
        // 保存缩略图和内容中上传的附件
        if (preg_match_all('#["\'](/storage/.+?\.[^"\']*)["\']#i', str_replace('\\', '', json_encode($data)), $matches)) {
            foreach (array_unique($matches[1]) as $match) {
                DB::table('files')->where('path', $match)->update(['status' => 0]);
            }
        }
        // 保存标签
        $tags = [];
        if (isset($data['tags']) && $data['tags']) {
            foreach (array_map('trim', array_unique(explode(',', $data['tags']))) as $tag_name) {
                $tag = DB::table('tag')->where('name', $tag_name)->first();
                if ($tag) {
                    // 已有标签
                    $tags[] = $tag->id;
                } else {
                    // 新标签
                    $tags[] = DB::table('tag')->insertGetId(['name' => $tag_name]);
                }
            }
        }
        $data['tags'] = json_encode($tags);
        DB::table('article')->where('id', $id)->update($data);
        return $this->errMsg(0, '修改成功');
    }

    public function del(Request $request)
    {
        $id = (array)$request->id;
        if (!$id) return $this->errMsg(1, '请选择数据');
        $res = DB::table('article')->whereIn('id', $id)->update(['is_del' => 1]);
        if (!$res) return $this->errMsg(1, '删除失败');
        return $this->errMsg(0, '删除成功');
    }
}
